<template>
  <el-dialog :visible.sync="dialogFormVisible" :title="textMap[dialogStatus]" :close-on-click-modal="false"
             width="600px">
    <el-form ref="dataForm" label-position="left" label-width="90px" :model="addUserForm"
             style='width: 400px; margin-left:50px;' :close-on-click-modal="false" :rules="rules" size="mini">
      <el-form-item v-if="dialogStatus === 'create'" label="用户名" prop="loginName">
        <el-input v-model="addUserForm.loginName"></el-input>
      </el-form-item>
      <el-form-item v-if="dialogStatus === 'create'" label="密码" prop="password">
        <el-input v-model="addUserForm.password" type="password"></el-input>
      </el-form-item>
      <el-form-item v-if="dialogStatus === 'create'" label="确认密码" prop="checkPass">
        <el-input v-model="addUserForm.checkPass" type="password"></el-input>
      </el-form-item>
      <el-form-item label="真实姓名" prop="name">
        <el-input v-model="addUserForm.name"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addUserForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="tel">
        <el-input v-model="addUserForm.tel"></el-input>
      </el-form-item>
      <el-form-item label="选择机构" prop="orgId">
        <treeselect placeholder="请选择机构" v-model="addUserForm.orgId" :multiple="false" :options="computedOptions"
                    @input="handleSelected" :load-options="loadOrgsOptions"/>
      </el-form-item>
      <el-form-item label="选择角色" prop="roleId">
        <treeselect placeholder="请选择角色" :multiple="true" value-consists-of="LEAF_PRIORITY"
                    :disable-branch-nodes="true" v-model="addUserForm.roleIds" :load-options="loadRolesOptions"
                    value-format="object" :options="groupslist"/>
      </el-form-item>
      <el-form-item label="继承权限" prop="isInherit">
        <el-select v-model="addUserForm.isInherit">
          <el-option v-for="item in isInheritOptions"
                     :value="item.value"
                     :label="item.label"
                     :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
      <el-button size="mini" v-if="dialogStatus === 'create'" type="primary" @click="createUser">确定</el-button>
      <el-button size="mini" v-if="dialogStatus === 'update'" type="primary" @click="updateUser">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { addUser, updateUser, getUserDetail } from '@/api/users'
  import { getOrgTree } from '@/api/orgs'
  import { getRoleGroupList, getRolesList } from '@/api/roles'
  import{ modifyObj, resetDataForm, covertArrParams } from '@/utils/tools'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
  const Md5 = require('blueimp-md5')
  import { k } from '@/utils/tools'

  export default {
    name: 'userDialog',
    components: {Treeselect},
    computed: {
      computedOptions(){
        return modifyObj(this.optionsOrgs)
      }
    },
    data(){
      return {
        groupslist: [],
        dialogStatus: '',//公用新建和编辑窗口
        dialogFormVisible: false,
        textMap: {
          update: '修改',
          create: '新建用户'
        },
        addUserForm: {//新建用户的data参数
          id: null,
          loginName: null,
          name: null,
          email: null,
          tel: null,
          roleIds: null,
          orgId: '',
          password: null,
          checkPass: null,
          isInherit: 0
        },
        rules: {
          loginName: [{required: true, message: '请填写用户名', trigger: 'blur'}],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (this.addUserForm.checkPass !== '') {
                  this.$refs.dataForm.validateField('checkPass')
                }
                callback()
              }, trigger: 'blur'
            }
          ],
          checkPass: [
            {required: true, message: '请再输入确认密码', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (value !== this.addUserForm.password) {
                  callback(new Error('两次输入密码不一致!'))
                } else {
                  callback()
                }
              }, trigger: 'blur'
            }
          ],
          orgId: [{required: true, message: '请选择机构ID'}],
          roleIds: [{required: true, message: '请选择角色'}],
          name: [{required: true, message: '请选择姓名', trigger: 'blur'}]
        },
        isInheritOptions: [
          {label: '继承', value: 0},
          {label: '不继承', value: 1}
        ],
        optionsOrgs: []
      }
    },
    methods: {
      //打开新建用户
      handleCreate(status, id) {
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          resetDataForm(this.$refs['dataForm'])
          this.addUserForm.orgId = null
          this.getOrgTree()
          this.getRoleGroupList()
        })
      },
      handleEdit(id){
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs['dataForm'].clearValidate()
          }, 50)
          this.getOrgTree()
          this.getRoleGroupList()
          this.getUserDetail(id)
        })
      },
      //提交表单
      createUser(){
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let _roleIdsArr = [], _paramObj = this.addUserForm
            _paramObj.roleIds.forEach(item => {
              _roleIdsArr.push(item.id)
            })
            _paramObj = Object.assign({}, _paramObj, {roleIds: _roleIdsArr.join(',')})

            _paramObj.password = Md5(_paramObj.password, k(), false)
            addUser(_paramObj).then(res => {
              res = res.data
              if (res.code === 200) {
                this.dialogFormVisible = false
                this.$emit('submited-user', res)
                this.$message({showClose: true, message: '创建成功', type: 'success'});
              } else {
                this.$message({showClose: true, message: res.message, type: 'error'});
              }
            })
          }
        })
      },
      updateUser(){
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let _roleIdsArr = [], _paramObj = this.addUserForm
            _paramObj.roleIds.forEach(item => {
              _roleIdsArr.push(item.id)
            })
            _paramObj = Object.assign({}, _paramObj, {roleIds: _roleIdsArr.join(',')})
            _paramObj = {
              id: this.addUserForm.id,
              tel: this.addUserForm.tel,
              name: this.addUserForm.name,
              email: this.addUserForm.email,
              roleIds: _paramObj.roleIds,
              orgId: this.addUserForm.orgId,
              isInherit: this.addUserForm.isInherit
            }
            updateUser(_paramObj).then(res => {
              this.$emit('submited-user', res)
              this.dialogFormVisible = false
              this.$message({showClose: true, message: '修改成功', type: 'success'});
            })
          }
        })
      },
      handleSelected(value){
        if (value !== undefined) {
          this.$refs['dataForm'].validateField('orgId')
        }
      },
      handleChange(value){
        console.log(value)
      },
      getOrgTree(){
        getOrgTree({
          pageSize: 9999
        }).then(res => {
          res = res.data
          this.optionsOrgs = res.data
        })
      },
      loadOrgsOptions({action, parentNode, callback, id}){
        callback()
      },
      loadRolesOptions({action, parentNode, callback, id}){
        if (action === LOAD_CHILDREN_OPTIONS) {
          let _arr = []
          getRolesList({parentId: parentNode.id, pageSize: 9999}).then(res => {
            res = res.data
            if (res.data.dataList !== '') {
              res.data.dataList.forEach(item => {
                _arr.push({id: item.id, label: parentNode.label + '-' + item.name})
              })
            }
            parentNode.children = _arr
            callback(null, _arr)
          })
        }
      },
      getRoleGroupList(){
        getRoleGroupList().then(res => {
          res = res.data
          if (res.data.dataList !== null || res.data.dataList !== '') {
            res.data.dataList.forEach(item => {
              item.children = null
              item.label = item.name
            })
          }
          this.groupslist = []
          setTimeout(() => {
            this.groupslist = res.data.dataList
          }, 50)
        })
      },
      getUserDetail(id){
        getUserDetail({id: id}).then(res => {
          res = res.data
          if (res.code === 200) {
            let {id, loginName, name, email, tel, roles, orgId, isInheritRoles} = res.data
            this.addUserForm = {
              id: id,
              loginName: null,
              name: name,
              email: email,
              tel: tel,
              isInherit: (isInheritRoles === null ? 0 : isInheritRoles),
              roleIds: null,
              orgId: orgId,
              password: null,
              checkPass: null
            }
//            this.addUserForm.roleIds = roleIds.join(',')
            let rolesArr = []
            if (roles !== null && roles !== '') {
              roles.forEach(item => {
                rolesArr.push({label: item.parentName + '-' + item.roleName, id: item.roleId})
              })
            }
            if (rolesArr.length > 0) {
              this.addUserForm.roleIds = []
              setTimeout(() => {
                console.log(rolesArr)
                this.addUserForm.roleIds = rolesArr
              }, 100)
            }
          }
        })
      }
    }
  }
</script>
